package com.itheima.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.commen.BaseContext;
import com.itheima.reggie.commen.CustomException;
import com.itheima.reggie.commen.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.ORB;
import org.omg.CORBA.REBIND;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private  AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    @Transactional
    public void submit(Orders orders) {
        //根据用户id查询出购物车信息
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> cartList = shoppingCartService.list(queryWrapper);

        //根据addressBookId，获取地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);

        //使用雪花算法生成id
        long orderId = IdWorker.getId();

        //保存订单表里面的信息
        orders.setId(orderId);
        orders.setNumber(String.valueOf(Math.random()*1000));
        orders.setStatus(2);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        orders.setUserName(addressBook.getProvinceName());
        orders.setConsignee(addressBook.getConsignee());

        //用来所有商品总和
        BigDecimal amount = BigDecimal.ZERO;

        //保存订单明细表的信息
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setImage(cart.getImage());
            orderDetail.setOrderId(orderId);

            //判断添加的是菜品还是套餐
            if (cart.getDishId()!=null){
                orderDetail.setDishId(cart.getDishId());
                orderDetail.setDishFlavor(cart.getDishFlavor());
            }else {
                orderDetail.setSetmealId(cart.getSetmealId());
            }
            orderDetail.setNumber(cart.getNumber());
            //计算单价和数量的相乘的价格
            BigDecimal result = BigDecimal.valueOf(cart.getNumber()).multiply(cart.getAmount());

            orderDetail.setAmount(result);
            amount = amount.add(result);
            orderDetailList.add(orderDetail);
        }

        orders.setAmount(amount);

        //保存订单表，订单明显表
        this.save(orders);
        orderDetailService.saveBatch(orderDetailList);

        //下单完成后，清空当前用户的购物车
        shoppingCartService.remove(queryWrapper);
    }
}